<template>
    <view class="page_root" data-page-name="新建请假日报（定制）" data-page-identification="d_2r2rm0jcc8">
        <!-- UNI_APP_EXEGESIS_START NAVIGATION_TEMPLATE UNI_APP_EXEGESIS_END -->
        <!-- begin vid_8b2j28qqan 自定义模板_kfixsg9c7g -->
        <view class="body">
            <view class="bgc-img"></view>
            {{ leaveRecordState.form }}
            <view
                style="background-color: #fff;padding: 15px;border-radius: 4px; height: calc(100vh - 250px); overflow: auto;">
                <view class="top-tip">
                    <view style="display: flex;">
                        <view class="now-img"></view> 正在编辑工时：<span class="weight-font">{{ leaveRecordState.editHour
                            }}小时</span>
                    </view>
                </view>
                <u-picker v-model="leaveRecordState.dateShow" mode="time" title="请选择工时对应时间" @confirm="onTimeConfirm"
                    @cancel="onCancel"></u-picker>
                <u-form-item required="true" label-position="top" label="请选择工时对应时间" prop="dailyDate" :rules="rules">
                    <u-input border="true" placeholder="请选择工时对应时间" type="select"
                        v-model:modelValue="leaveRecordState.dailyDate"
                        @click="leaveRecordState.dateShow = true"></u-input>
                </u-form-item>
                <view class="task-daily">
                    <u-form :model="leaveRecordState.form" ref="taskDailyRef">
                        <view class="task-daily-item">
                            <u-form-item label-position="top" label="请选择休假开始时间" required="true">
                                <u-input border="true" v-model:modelValue="leaveRecordState.form.startDate"
                                    @click="showLeaveDate('start')" type="select" class="input-disabled" style="margin-right: 10px;" />
                                <u-input border="true" type="select"
                                    v-model:modelValue="leaveRecordState.form.startCategory" class="input-disabled"
                                    @click="showLeaveCategory('start')" />
                                <u-select v-model="leaveRecordState.categoryShow" :title="leaveRecordState.title"
                                    :list="[{ value: 'AM', label: '上午' }, { value: 'PM', label: '下午' }]"
                                    @confirm="categoryConfirm" />
                            </u-form-item>
                            <u-form-item label-position="top" label="请选择休假结束时间" required="true">
                                <u-input border="true" v-model:modelValue="leaveRecordState.form.endDate" placeholder="请选择日期" type="select" style="margin-right: 10px;"
                                    @click="showLeaveDate('end')" class="input-disabled" />
                                <u-picker v-model="leaveRecordState.leaveDateShow" mode="time"
                                    :title="leaveRecordState.title" @confirm="leaveTimeConfirm" @cancel="onCancel" />
                                <u-input border="true" v-model:modelValue="leaveRecordState.form.endCategory"
                                    @click="showLeaveCategory('end')" type="select" class="input-disabled" />
                            </u-form-item>
                        </view>
                    </u-form>
                </view>
                <!-- end -->
            </view>
            <u-row justify="space-around" style="margin-top: 12px">
                <u-col span="4">
                    <u-button :custom-style="customStyle" @click="handlerCancel">取消</u-button>
                </u-col>
                <u-col span="4">
                    <u-button :custom-style="customStyle" @click="handlerSubmit(false)">保存</u-button>
                </u-col>
                <u-col span="4">
                    <u-button :custom-style="customStyle" @click="handlerSubmit(true)">保存并提交</u-button>
                </u-col>
            </u-row>
        </view>

        <u-modal title="请确认" v-model="leaveRecordState.show" show-cancel-button @confirm="handleConfirmSubmit"
            :title-style="{ padding: 0, marginTop: '10px', marginBottom: '10px' }">
            <view class="sub-tip">
                <view class="sub-title">
                    正在提交工时：{{ leaveRecordState.editHour }}工时 <br />
                    今日已提交总工时(不含本次提交)：{{ leaveRecordState.allHours }}工时</view>
            </view>
        </u-modal>
        <!-- end vid_8b2j28qqan 自定义模板_kfixsg9c7g -->
    </view>
</template>
<script setup>

import {
    ref, reactive, toRaw, markRaw,
    watch, computed,
    onBeforeMount, onMounted, onBeforeUnmount, onUnmounted, onActivated, onDeactivated, getCurrentInstance
} from "vue";
import { useRoute } from 'vue-router';
const route = useRoute();
import { get, post, put, del, request, requestWithHeaders } from '@/utils/http/Axios';
import { cloneDeep, localGet, traversalTreeStructure, set, checkCaseCondition, throttle, merge, debounce, getGridStyle, getCellRenderAble } from '@/utils/index';
import { isEqual, isNullOrEmpty, isEmptyArr, isArray, isEmpty, isNullOrUnDef, isContained } from '@/utils/is';
import { CovertOptions, getChartsDataSourceConvert } from '@/utils/chart';
import { propertyFormatByNumber, propertyFormatByPercentage, propertyFormatByDate, } from '@/utils/format';
import { FormFormat } from '@/utils/formFormat'
import { customAddWaterMarkFunc, generateWaterMarkText } from '@/utils/addWaterMark';
import dayjs from 'dayjs';
import hashSum from 'hash-sum';
import { onPullDownRefresh, onLoad, onReady, onShow, onHide, onPageScroll, onUnload } from '@dcloudio/uni-app';
/*** UNI_APP_EXEGESIS ***
import { handleRedirect, permission, parseJson } from '@/utils/common';
import { onPullDownRefresh, onLoad, onReady, onShow, onHide, onPageScroll, onUnload } from '@dcloudio/uni-app';
import { BroadcastMessage } from '@/utils/BroadcastMessage';
import { sendToken } from "@/hooks/useIframeToken";
*** UNI_APP_EXEGESIS ***/


// ---------------------------- 属性定义 ----------------------------
const sourceId = "page3000000511"

// 获取传入的流程ID和组件参数
const props = defineProps({
    'processInstanceId': {
        type: [String, Number, Boolean],
        default: undefined,
    },
    'hideNav': {
        type: [Boolean],
        default: undefined,
    },
})


// 组件参数默认值
const componentParamsDefaultProps = {

}


// 是否显示菜单按钮
const isMenuIconShow = false;
// NAVIGATION_MENU
const handleShowNavigation = () => { };

let isProcessState = ref(false);


const setTimeOutList = [];


const vid_8b2j28qqan_props = reactive({
    code: "",
});



// ============================ 属性定义 ============================

// ---------------------------- 元素数据引用 ----------------------------
// 组件 自定义模板_kfixsg9c7g ref 的引用
const vid_8b2j28qqan_ref = ref(null);
// 动态key的map
const fieldTypeMap = {};
// 动态key的map
const refMap = { vid_8b2j28qqan_ref };

const showState = reactive({
    vid_8b2j28qqan_visible: true,
})
// ============================ 元素数据引用 ============================

// ---------------------------- 数据 ----------------------------


// ============================ 数据 ============================

// ---------------------------- 方法 ----------------------------
// ---------------------------- 页面数据 ----------------------------


// ============================ 页面数据 ============================

// ---------------------------- 数据字典 ----------------------------


// ============================ 数据字典 ============================

// ---------------------------- 响应 ----------------------------

// ============================ 响应 ============================

// ---------------------------- 函数 ----------------------------

// 自定义函数 返回上一页
const customFunction_goBack_1ceedl2kx3 = (params) => {
    uni.navigateBack()
}

// ============================ 函数 ============================

// ---------------------------- 页面参数 ----------------------------

const pageParameter_state = reactive({
    'processInstanceId': undefined,
})

// ============================ 页面参数 ============================

// ---------------------------- 组件事件处理方法 ----------------------------


// ============================ 组件事件处理方法 ============================

// ============================ 方法 ============================

// ---------------------------- 生命周期 ----------------------------
/*** UNI_APP_EXEGESIS ***
    // 获取上一层传递的数据
    const workflowChannel = new BroadcastMessage('WORKFLOW');
    workflowChannel.publish({ status: 'Ready' });
    workflowChannel.subscribe((data) => {
      if (data) {
        isProcessState.value = (window.self !== window.parent && data.type === 'hideHeader');
      }
    });
    *** UNI_APP_EXEGESIS ***/


const pageScrollTop = ref(0)

// *** PREVIEW_EXEGESIS ***
onMounted(() => {
    setPageParams(route.query)
    // 设置表单的rule
    try {

    } catch {
        // do nothing
    }
});
// *** PREVIEW_EXEGESIS *** //

/*** UNI_APP_EXEGESIS ***
const routeOption = ref({})
onLoad((option) => {
  routeOption.value = option;
});
onReady(() => {
  setPageParams(routeOption.value)
  // 设置表单的rule
  try{
 
  }catch{
      // do nothing
  }
});
// 图表刷新标记
const uChartsReshowFlag = ref(false);
onHide(() => { // 页面隐藏后标记置为false(如果不置为false无法触发图表更新)
    uChartsReshowFlag.value = false
})
onShow(() => {
    uChartsReshowFlag.value = true; // 页面激活后,标记置为true
 
    setPageParams(routeOption.value)
})
onPageScroll(e => {
    pageScrollTop.value = e.scrollTop
});
*** UNI_APP_EXEGESIS ***/

const setPageParams = (routerParam) => {
    const pageParams = [{ "dataType": "STRING", "name": "processInstanceId" }];
    const strategyMap = {
        STRING: (param, paramValue) => {
            pageParameter_state[param.name] = paramValue;
        },
        BOOLEAN: (param, paramValue) => {
            if ('true' === (paramValue || '').toLowerCase()) {
                pageParameter_state[param.name] = true
            } else if ('false' === (paramValue || '').toLowerCase()) {
                pageParameter_state[param.name] = false
            } else {
                // TODO: 是否要支持toast
                console.error('参数传入错误！类型不匹配！');
            }
        },
        NUMBER: (param, paramValue) => {
            if (!isNaN(paramValue)) {
                pageParameter_state[param.name] = Number(paramValue);
            } else {
                // TODO: 是否要支持toast
                console.error('参数传入错误！类型不匹配！');
            }
        },
        ARRAY: (param, paramValue) => {
            if (isNullOrUnDef(paramValue) || !paramValue || paramValue === 'undefined') { // default value
                pageParameter_state[param.name] = [];
            } else if (paramValue.trim().startsWith('[') && paramValue.trim().endsWith(']')) {
                try {
                    pageParameter_state[param.name] = JSON.parse(decodeURI(paramValue));
                } catch (error) {
                    console.error('参数解析失败 ', error);
                }
            } else {
                console.error('参数传入错误！类型不匹配！');
            }
        },
    };
    pageParams.forEach((param) => {
        strategyMap[param.dataType](param, routerParam[param.name])
    });


}

onUnmounted(() => {
    // 销毁定时器
    setTimeOutList.forEach(({ repeat, timer }) => {
        repeat ? clearInterval(timer) : clearTimeout(timer);
    });
});


/*** UNI_APP_EXEGESIS ***
onPullDownRefresh(() => {
  // 下拉刷新
  setTimeout(() => {
      uni.stopPullDownRefresh()
  }, 1000)
})
*** UNI_APP_EXEGESIS ***/

// ============================ 生命周期 ============================

// ---------------------------- 数据关联处理 ----------------------------
// ---------------------------- 组件数据同步 ----------------------------

// ============================ 组件数据同步 ============================
//
// ============================ 数据关联处理 ============================

// ---------------------- 不同组件自定义的处理逻辑 ---------------------

// ====================== 不同组件自定义的处理逻辑 ======================


// ================================定制化逻辑========================================
onMounted(() => {
    let appDiv = document.querySelector('#app');
    if (appDiv) appDiv.style.background = 'linear-gradient(180deg, #E1EFFD 100%, #ffffff 0%)';
    let topHeader = document.querySelector('.uni-page-head');
    if (topHeader) topHeader.remove()
    let bottomTab = document.querySelector('.vid_dur3o27gyj')
    if (bottomTab) bottomTab.remove()
    let warpper = document.querySelector('uni-page-wrapper')
    if (warpper) warpper.style.height = '100%';
    post('/solution-ppm/api/v2/built-in-system-ppm/daily_report/for_create', { dailyDate: leaveRecordState.dailyDate }).then(data => {
        leaveRecordState.allHours = data.data.workHours
    })
   
})
const rules = {
    dailyDate: [{ type: 'string', required: true, message: '请选择工时对应时间', trigger: 'blur' }],
    startDate: [{ type: 'string', required: true, message: '请选择休假开始时间', trigger: 'blur' }],
    startCategory: [{ type: 'string', required: true, message: '请选择休假开始时间', trigger: 'blur' }],
    endDate: [{ type: 'string', required: true, message: '请选择休假结束时间', trigger: 'blur' }],
    endCategory: [{ type: 'string', required: true, message: '请选择休假结束时间', trigger: 'blur' }],
};
const leaveRecordState = reactive({
    visible: false,
    editHours: undefined,
    allHours: undefined,
    confirmVisible: false,
    disabled: true,
    topList: [`正在编辑工时：0工时,今日已提交总工时（不含本次提交）0工时`],
    editHour: 0,
    show: false,
    dailyDate: '',
    dateShow: false,
    title: '',
    isSaveAndSubmit: false,
    form: {
        startDate: '',
        startCategory: '上午',
        endDate: '',
        endCategory: '上午'
    },
    timeFlag: '',
    categoryFlag: '',
    leaveDateShow: false,
    categoryShow: false
})
watch(
  () => [leaveRecordState.form.startDate, leaveRecordState.form.startCategory, leaveRecordState.form.endDate, leaveRecordState.form.endCategory],
  ([newStartDate, newstartCategory, newEndDate, newendCategory]) => {
    if (newStartDate && newstartCategory && newEndDate && newendCategory) {
        if (dayjs(newStartDate).format('YYYY-MM-DD') > dayjs(newEndDate).format('YYYY-MM-DD') ){
            uni.showToast({
                title: '休假开始时间不能晚于休假结束时间',
                icon: 'error'
            });
            leaveRecordState.form.endDate=''
        }else{
            post('/solution-ppm/api/v2/built-in-system-ppm/daily_report/holiday_report/duration_days',convertTimeCategories(leaveRecordState.form)).then(data=>{
        leaveRecordState.editHour = data.data
      })
        }

    }
  },
  { immediate: true }
);
function convertTimeCategories(data) {
    const convertedData = { ...data }; // 复制输入数据，避免修改原始数据

    if (convertedData.startCategory === '上午') {
        convertedData.startCategory = 'AM';
    } else if (convertedData.startCategory === '下午') {
        convertedData.startCategory = 'PM';
    }

    if (convertedData.endCategory === '上午') {
        convertedData.endCategory = 'AM';
    } else if (convertedData.endCategory === '下午') {
        convertedData.endCategory = 'PM';
    }

    return convertedData;
}



const formattedDate = dayjs().format('YYYY-MM-DD');
leaveRecordState.dailyDate = formattedDate;
leaveRecordState.form.startDate = formattedDate;
function showLeaveDate(flag) {
    leaveRecordState.timeFlag = flag
    if (flag === 'start') {
        leaveRecordState.title = '请选择休假开始时间'
    } else {
        leaveRecordState.title = '请选择休假结束时间'
    }
    leaveRecordState.leaveDateShow = true
}
const customStyle = reactive({
    backgroundColor: '#008BFF',
    color: '#fff',
    borderRadius: '4px',
});
function showLeaveCategory(flag) {
    leaveRecordState.categoryFlag = flag
    if (flag === 'start') {
        leaveRecordState.title = '请选择休假开始时间'
    } else {
        leaveRecordState.title = '请选择休假结束时间'
    }
    leaveRecordState.categoryShow = true
}
function onTimeConfirm(params) {
    leaveRecordState.dailyDate = `${params.year}-${params.month}-${params.day}`;

}
function leaveTimeConfirm(params) {
    if (leaveRecordState.timeFlag === 'start') {
        leaveRecordState.form.startDate = `${params.year}-${params.month}-${params.day}`;
    } else {
        leaveRecordState.form.endDate = `${params.year}-${params.month}-${params.day}`;
    }
}
function categoryConfirm(params) {
    if (leaveRecordState.timeFlag === 'start') {
        leaveRecordState.form.startCategory = params[0].label
    } else {
        leaveRecordState.form.endCategory = params[0].label
    }
}
function handlerSubmit(flag) {
    console.log(leaveRecordState.form.startDate && leaveRecordState.form.startCategory && leaveRecordState.form.endDate && leaveRecordState.form.endCategory);
    if (leaveRecordState.form.startDate && leaveRecordState.form.startCategory && leaveRecordState.form.endDate && leaveRecordState.form.endCategory) {
        leaveRecordState.isSaveAndSubmit = flag
            if (leaveRecordState.isSaveAndSubmit) {
                leaveRecordState.show = true
            } else {
                handleConfirmSubmit()
            }
    } else {
        uni.showToast({
            title: '请补充休假时间',
            icon: 'error'
        });
    }

}
function handleConfirmSubmit() { }
</script>
<style lang="less" scoped>
.page_root {
    min-height: 100%;
    box-sizing: border-box;
    overflow: auto;
}

.body {
    height: 100%;
    padding: 15px;
    border-top-left-radius: 16px;
    border-top-right-radius: 16px;
    position: relative;
    background: linear-gradient(180deg, #e1effd 100%, #ffffff 0%);
    z-index: 1;
    top: -10px;
}

.bgc-img {
    position: absolute;
    width: 100%;
    height: 300px;
    left: 0;
    top: -1px;
    background-image: url('http://10.40.0.33:9001/file-storage/437915688640577536.png');
    background-size: cover;
    z-index: -1;
    border-top-left-radius: 16px;
    border-top-right-radius: 16px;
}

.page_root {
    min-height: 100%;
    box-sizing: border-box;
    background: linear-gradient(180deg, #e1effd 100%, #ffffff 0%);
}

.top-tip {
    height: 48px;
    width: 100%;
    background-image: url('http://10.40.0.33:9001/file-storage/440282587716255744.png');
    background-size: cover;
    padding: 13px 15px;
    border-radius: 4px;
    border-right: 1px solid #99B9FF;
}

.now-img {
    margin-top: 2px;
    margin-right: 8px;
    height: 18px;
    width: 18px;
    background-image: url("http://10.40.0.33:9001/file-storage/440283167798984704.png");
    background-size: cover;
}

.today-img {
    margin-top: 2px;
    margin-right: 8px;
    height: 18px;
    width: 18px;
    background-image: url("http://10.40.0.33:9001/file-storage/440283179299766272.png");
    background-size: cover;
}

.weight-font {
    color: #3875ff;
    font-weight: 600;
}

.sub-title {
    padding: 0 15px;
    font-size: 14px;
}
</style>